import UIKit
import MJRefresh
import SnapKit

class BaseVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate {

    

    var page = 1
    
    var tableStytle: UITableView.Style = .grouped
    
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: view.frame.height))
        scrollView.delegate = self
        scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height + 1)
        view.addSubview(scrollView)
        return scrollView
    }()
    
    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        return layout
    }()
    
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        view.addSubview(collectionView)
        return collectionView
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), style: tableStytle)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.sectionIndexBackgroundColor = .clear
        tableView.sectionIndexColor = kGrayBG
        tableView.separatorStyle = .singleLine
        tableView.separatorColor = kGrayBG
        tableView.backgroundColor = kGrayBG
        
//        if #available(iOS 15.0, *) {
//            tableView.sectionHeaderTopPadding = 0
//            tableView.sectionFooterHeight = 0
//        }
        
//        UIColor(red: 244/255, green: 244/255, blue: 244/255, alpha: 1)
        
        if #available(iOS 11.0, *) {
            tableView.estimatedRowHeight = 0
            tableView.estimatedSectionFooterHeight = 0
            tableView.estimatedSectionHeaderHeight = 0
        }
        
        
        
        if #available(iOS 11.0, *) {
//            tableView.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
            } else {
                // Fallback on earlier versions
            }
        view.addSubview(tableView)
        return tableView
    }()
    
    lazy var nullView : UIImageView = {
        let nullView = UIImageView.init(frame: CGRect(x: kScreenWidth / 2 - 100, y: GKNavHeight + 150, width: 200, height: 200))
        nullView.image = UIImage(named: "nullData")
        view.addSubview(nullView)
        return nullView
    }()

    lazy var dataSource: [Any] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        navigationController?.interactivePopGestureRecognizer?.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    func getData() {}

    func handleDatas(_ datas: [Any]?, withPageCount pageCount: Int) {
        // Implementation here...
    }

    func handleCollectionDatas(_ datas: [Any]?, withPageCount pageCount: Int) {
        // Implementation here...
    }
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        
        view.tintColor = UIColor.clear
        
    }
    
    func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        
        view.tintColor = UIColor.clear
        
    }

    func setupRefreshTableView() {
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshData))
        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
    }

    func setupRefreshCollectionView() {
        collectionView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshData))
        collectionView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
    }

    @objc func refreshData() {
        page = 1
        getData()
    }

    @objc func loadMoreData() {
        page += 1
        getData()
    }

//     Table View Data Source Methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    // Collection View Data Source Methods
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return UICollectionViewCell()
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }

    func registerCell(withNibName nibName: String, isTableView: Bool) {
        if isTableView {
            tableView.register(UINib(nibName: nibName, bundle: nil), forCellReuseIdentifier: nibName)
        } else {
            collectionView.register(UINib(nibName: nibName, bundle: nil), forCellWithReuseIdentifier: nibName)
        }
    }

    func registerCell(withClassName className: String?, isTableview isTableView: Bool) {
        if isTableView {
            tableView.register(NSString.self, forCellReuseIdentifier: className ?? "")
        } else {
            collectionView.register(NSString.self, forCellWithReuseIdentifier: className ?? "")
        }
    }

    func registerHeaderFooter(withClassName className: String) {
        tableView.register(NSString.self, forHeaderFooterViewReuseIdentifier: className)
    }

    func registerHeaderFooter(withNibName nibName: String) {
        tableView.register(UINib(nibName: nibName, bundle: nil), forHeaderFooterViewReuseIdentifier: nibName)
    }

    func registerHeader(withClassName className: String) {
        collectionView.register(NSString.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: className)
    }

    func registerFooter(withClassName className: String) {
        collectionView.register(NSString.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: className)
    }

    func registerHeader(withNibName nibName: String) {
        collectionView.register(UINib(nibName: nibName, bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: nibName)
    }

    func registerFooter(withNibName nibName: String) {
        collectionView.register(UINib(nibName: nibName, bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: nibName)
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay supplementaryView: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
        if #available(iOS 11.0, *) {
            if elementKind == UICollectionView.elementKindSectionHeader {
                supplementaryView.layer.zPosition = 0
            }
        }
    }

    func rt_customBackItemWithTarget(_ target: Any?, action: Selector, image: String) -> UIBarButtonItem {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: image), for: .normal)
        btn.sizeToFit()
        btn.addTarget(target, action: action, for: .touchUpInside)
        return UIBarButtonItem(customView: btn)
    }
    
    func rt_textItemWithTarget(_ target: Any?, action: Selector, title: String) -> UIBarButtonItem {
        let btn = UIButton(type: .system)
//        btn.setImage(UIImage(named: image), for: .normal)
        btn.setTitle(title, for: .normal)
        btn.tintColor = UIColor.black
        btn.titleLabel?.textColor = UIColor.black
        btn.sizeToFit()
        btn.addTarget(target, action: action, for: .touchUpInside)
        return UIBarButtonItem(customView: btn)
    }

    deinit {
        print("======dealloc===\(type(of: self))===")

    }

    func invitedCode(_ code: NSNumber?) -> Bool {
        guard let codeValue = code else { return false }

        switch codeValue.intValue {
        case 200, 0:
            return true
        default:
            return false
        }
    }
    
    func fetchDataFromURL(url: String?, completionHandler: @escaping ([String]?, Error?) -> Void) {
        guard let url = URL(string: url ?? "") else {
            completionHandler(nil, NSError(domain: "com.yueliao.ios", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]))
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                completionHandler(nil, error)
                return
            }

            guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                  let array = json["data"] as? [String] else {
                completionHandler(nil, NSError(domain: "com.yueliao.ios", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to parse JSON"]))
                return
            }

            completionHandler(array, nil)
        }.resume()
    }
    
    
    // 验证手机号码是否有效
    func isValidPhoneNumber(phoneNumber: String) -> Bool {
        let phoneRegex = "^1[3-9]\\d{9}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: phoneNumber)
    }
    
    func presentVC(VC : UIViewController) {
        if #available(iOS 13.0, *) {
            VC.modalPresentationStyle = .overFullScreen
        } else {
            VC.modalPresentationStyle = .fullScreen
        }
        self.present(VC, animated: true, completion: nil)
    }
    
    func dismiss () {
        if self.presentingViewController != nil {
            dismiss(animated: true)
        }else {
            navigationController?.popViewController(animated: true)
        }
    }
    
}
